package com.yunfeng.supercall.activity;

import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.lin.action.UIDfineAction;
import com.lin.utils.Parameters;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.PinterestCircleBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yzx.api.CallType;
import com.yzx.api.UCSCall;

/**
 * 呼入呼出电话的基类
 * 
 * @author 洋
 * 
 */
@SuppressLint("Wakelock")
public class BaseCallActivity extends BaseActivity implements
SensorEventListener {
	
	SuperFriendsBean mSuperFriends;


	protected TextView mTextView;// 标题栏的text
	private WakeLock mWakeLock;
	private WakeLock mWakeLockScreen;
	KeyguardManager mKeyguardManager; // 键盘锁
	private KeyguardLock mKeyguardLock;
	// 调用距离传感器，控制屏幕
	private SensorManager mManager;// 传感器管理对象
	// 屏幕开关
	private PowerManager localPowerManager = null;// 电源管理对象
	ScreenStateListener mScreenStateListener;
	private CallStateReceiver mCallStateReceiver;
	protected TextView mTextViewCallTime;// 记录通话时间

	DisplayImageOptions options;

	
	int stateint = -1;
	/**
	 * 获取这个人的详情后刷新界面
	 * 
	 * @param friends
	 */
	public void refreshView(SuperFriendsBean friends) {
		options = new DisplayImageOptions.Builder()
		.displayer(new PinterestCircleBitmapDisplayer(getResources().getDimensionPixelSize(R.dimen.corners_avatar)))
		.showImageOnFail(R.drawable.bg_share_header)
		.showImageOnLoading(R.drawable.bg_share_header)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();

		TextView name = findView(R.id.tv);
		TextView level = findView(R.id.level);
		ImageView imageView = (ImageView) findViewById(R.id.iv);
		ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + friends.getPhoto(), imageView, options);
		if (friends.getSucolor() == 0) {
			name.setTextColor(getResources().getColor(R.color.white));
			level.setTextColor(getResources().getColor(R.color.white));
		}

		setLevelColor(friends.getSucolor(), name, level);

	}

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mScreenStateListener = new ScreenStateListener();
		IntentFilter mFilter = new IntentFilter();
		mFilter.addAction(Intent.ACTION_SCREEN_OFF);
		mFilter.addAction(Intent.ACTION_SCREEN_ON);
		registerReceiver(mScreenStateListener, mFilter);
		localPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
		mWakeLock = localPowerManager.newWakeLock(
				PowerManager.ACQUIRE_CAUSES_WAKEUP
				| PowerManager.SCREEN_DIM_WAKE_LOCK,
				"PostLocationService");
		mWakeLockScreen = localPowerManager.newWakeLock(32, "screen");
		if (null != mWakeLock) {
			mWakeLock.acquire();
		}
		// 初始化键盘锁
		mKeyguardLock = mKeyguardManager.newKeyguardLock("");
		// 键盘解锁
		mKeyguardLock.disableKeyguard();
		mCallStateReceiver = new CallStateReceiver();
		IntentFilter ift = new IntentFilter();
		ift.addAction(ACTION_DIAL_STATE);
		ift.addAction(ACTION_CALL_BACK);
		ift.addAction(ACTION_ANSWER);
		ift.addAction(ACTION_CALL_TIME);
		registerReceiver(mCallStateReceiver, ift);
		com.yzx.api.UCSCall.setMicMute(false);
		com.yzx.api.UCSCall.setSpeakerphone(false);
//		com.yzx.api.UCSCall.initCameraConfig(OutCallActivity.this, remotelayout, locallayout);
	}

	public void handFree(View v) {
		v.setSelected(!v.isSelected());
		com.yzx.api.UCSCall.setSpeakerphone(v.isSelected());
	}

	public void soundOff(View v) {
		v.setSelected(!v.isSelected());
		com.yzx.api.UCSCall.setMicMute(v.isSelected());
	}

	@Override
	public void onSupportContentChanged() {
		super.onSupportContentChanged();
		mTextView = findView(R.id.title);
		mTextViewCallTime = findView(R.id.call_time);
		findView(R.id.back_button).setVisibility(View.GONE);
	}

	public void startListenSensor() {
		mManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		mManager.registerListener(this,
				mManager.getDefaultSensor(Sensor.TYPE_PROXIMITY),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	protected void onResume() {
		super.onResume();

	}

	private int mTime = 0;
	private Timer mTimer;
	private TimerTask mTimerTask;
	private Handler mHandler = new Handler();

	public void startCountUp() {
		stopCountUp();
		mTextViewCallTime.setVisibility(View.VISIBLE);
		mTimer = new Timer();
		mTimerTask = new TimerTask() {

			@Override
			public void run() {
				mTime++;
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						if (mTime < 10) {
							mTextViewCallTime.setText("00:0" + mTime);
						} else if (mTime < 60) {
							mTextViewCallTime.setText("00:" + mTime);
						} else if (mTime == 60) {
							mTextViewCallTime.setText("01:00");
						} else {
							int time = mTime % 60;
							int minute = mTime / 60;
							String min = "";
							if (minute < 10) {
								min = "0" + minute;
							} else {
								min = minute + "";
							}
							if (time < 10) {
								mTextViewCallTime.setText(min + ":0" + mTime
										% 60);
							} else {
								mTextViewCallTime.setText(min + ":" + mTime
										% 60);
							}

						}
					}
				});
			}
		};
		mTimer.schedule(mTimerTask, 0, 1000);
	}

	public void addCallTime() {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_time", mTime);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_ADD_CALL_TIME, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {

			}

			@Override
			public void onReceiveData(String data, String msg) {

			}
		});
	}

	@Override
	public void onBackPressed() {
	}

	public void stopCountUp() {
		findView(R.id.call_time).setVisibility(View.INVISIBLE);
		if (mTimer != null) {
			mTimer.cancel();
		}
		if (mTimerTask != null) {
			mTimerTask.cancel();
		}
		mTime = 0;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		com.yzx.api.UCSCall.hangUp("");
		releaseWakeLock();
		stopCountUp();
		unregisterReceiver(mScreenStateListener);
		unregisterReceiver(mCallStateReceiver);
	}

	// 释放设备电源锁
	private void releaseWakeLock() {
		if (null != mWakeLock) {
			if (mWakeLock.isHeld()) {
				mWakeLock.release();
			}
			mWakeLock = null;
		}
		if (mKeyguardLock != null) {
			mKeyguardLock.reenableKeyguard();
			mKeyguardLock = null;
		}
		if (mManager != null) {
			if (mWakeLockScreen.isHeld()) {
				mWakeLockScreen.release();
			}
			mWakeLockScreen = null;
			mManager.unregisterListener(this);// 注销传感器监听
		}
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		float[] its = event.values;
		// Log.d(TAG,"its array:"+its+"sensor type :"+event.sensor.getType()+" proximity type:"+Sensor.TYPE_PROXIMITY);
		if (its != null && event.sensor.getType() == Sensor.TYPE_PROXIMITY) {

			System.out.println("its[0]:" + its[0]);

			// 经过测试，当手贴近距离感应器的时候its[0]返回值为0.0，当手离开时返回1.0
			if (its[0] == 0.0) {// 贴近手机

				System.out.println("hands up");
				if (mWakeLockScreen.isHeld()) {
					return;
				} else {

					mWakeLockScreen.acquire();// 申请设备电源锁
				}
			} else {// 远离手机

				System.out.println("hands moved");
				if (mWakeLockScreen.isHeld()) {
					return;
				} else {
					mWakeLockScreen.setReferenceCounted(false);
					mWakeLockScreen.release(); // 释放设备电源锁
				}
			}
		}
	}

	/**
	 * 当对方应答
	 */
	public void onAnswer() {

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	/**
	 * 处理对方用户不在线
	 */
	public void handleOffLineUser() {

	}

	/**
	 * 挂断电话时
	 */
	public void onHangUp() {

	}

	/**
	 * 对方挂断电话时
	 */
	@SuppressLint("Wakelock")
	public void onOtherHangUp() {

	}

	/**
	 * 呼叫超时
	 */
	public void onTimeOut() {

	}

	/**
	 * 监听屏幕熄灭
	 * 
	 * @author 洋
	 * 
	 */
	public class ScreenStateListener extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				com.yzx.api.UCSCall.stopRinging();
			}
		}

	}

	/**
	 * 监听云之讯返回的状态码
	 * 
	 * @see com.yunfeng.supercall.service.CallConnectionService#onDialFailed(String,
	 *      com.yzx.listenerInterface.UcsReason)
	 * @author 洋
	 * 
	 */
	public class CallStateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Constants.ACTION_DIAL_STATE)) {
				int state = intent.getIntExtra("state", 0);
				/*if (state == com.yzx.api.UCSCall.CALL_VOIP_BUSY) {
					mTextView.setText("对方正在忙");
				}*/
				if (dialState.keySet().contains(state)) {

					if (state == com.yzx.api.UCSCall.CALL_VOIP_NUMBER_ERROR) {
						handleOffLineUser();
					} else if (state == com.yzx.api.UCSCall.CALL_VOIP_NETWORK_TIMEOUT) {
						onTimeOut();
					} else {
						mTextView.setText(dialState.get(state));
					}
				} else {
					if (state >= 300233 && state <= 300250) {
						switch (state) {
						// case 300010:session过期
						case 300211:
							mTextView.setText("余额不足");
							break;
						case 300219:
							mTextView.setText("不能拨打自己绑定号码");
							break;
						case 300233:
							mTextView.setText("回拨主叫没有绑定手机号码");
							break;
						case 300234:
							mTextView.setText("回拨绑定手机号码异常");
							break;
						case 300235:
							mTextView.setText("回拨鉴权错误");
							break;
						case 300236:
							mTextView.setText("回拨IO错误");
							break;
						case 300237:
							mTextView.setText("回拨请求成功但反回JSON错误");
							break;
						case 300238:
							mTextView.setText("回拨请求超时");
							break;
						case 300239:
							mTextView.setText("回拨服务器繁忙");
							break;
						case 300240:
							mTextView.setText("回拨服务器内部错误");
							break;
						case 300241:
							mTextView.setText("回拨被叫号码错误");
							break;
						case 300242:
							mTextView.setText("充值后才可以拨打国际电话");
							break;
						case 300243:
							mTextView.setText("回拨未知错误");
							break;
						case 300247:
							mTextView.setText("对方正在响铃");
							break;
						default:
							mTextView.setText("回拨未知错误");
							break;
						}
					}
				}

				if (state == com.yzx.api.UCSCall.HUNGUP_REFUSAL
						|| state == com.yzx.api.UCSCall.HUNGUP_MYSELF
						|| state == com.yzx.api.UCSCall.HUNGUP_OTHER
						|| state == com.yzx.api.UCSCall.HUNGUP_MYSELF_REFUSAL
						) {
					com.yzx.api.UCSCall.stopRinging();
					if (state == com.yzx.api.UCSCall.HUNGUP_REFUSAL) {
						mTextView.setText("对方拒绝接听");
						stateint = 1;
					} else {
						stateint = 2;
						mTextView.setText("已挂断");
						onOtherHangUp();
					}
					onHangUp();
					/** 1.5秒后结束此activity */
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							finish();
						}
					}, 1500);
				}

				if  (state == com.yzx.api.UCSCall.CALL_VOIP_BUSY||state == com.yzx.api.UCSCall.CALL_VOIP_NUMBER_ERROR	) {
					stateint = 0;
					com.yzx.api.UCSCall.stopRinging();
					onHangUp();
//					mTextView.setText("对方正忙");
					/** 1.5秒后结束此activity */
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							UCSCall.dial(getActivity(), CallType.VOIP, mSuperFriends.getVo_id());
							UCSCall.setSpeakerphone(false);
							sendBroadcast(new Intent(UIDfineAction.ACTION_DIAL).putExtra(UIDfineAction.CALL_UID, mSuperFriends.getVo_id()).putExtra("type",1));
//							finish();
						}
					}, 0);
//					}, 1500);
				}

			} else if (intent.getAction().equals(Constants.ACTION_ANSWER)) {
				onAnswer();
			}

		}
	}
	void setLevelColor(int level,TextView tvUserName, TextView tvPhone) {
		try {

			if(level == 0) {
				tvPhone.setTextColor(getResources().getColor(R.color.white));
				tvUserName.setTextColor(getResources().getColor(R.color.white));	
			} else if(level == 1) {
				tvPhone.setTextColor(getResources().getColor(R.color.level_or));
				tvUserName.setTextColor(getResources().getColor(R.color.level_or));
			} else {
				tvPhone.setTextColor(getResources().getColor(R.color.level_red));
				tvUserName.setTextColor(getResources().getColor(R.color.level_red));
			}
		} catch(NullPointerException e) {

		}
	}
	public SuperFriendsBean getmSuperFriends() {
		return mSuperFriends;
	}

	public void setmSuperFriends(SuperFriendsBean mSuperFriends) {
		this.mSuperFriends = mSuperFriends;
	}

}
